<?php

/**
 * This is the model class for table "news".
 *
 * The followings are the available columns in table 'news':
 * @property integer $id
 * @property integer $category_id
 * @property string $title
 * @property string $alt_title
 * @property string $image
 * @property string $short_story
 * @property string $full_story
 * @property string $date
 * @property string $keywords
 * @property string $description
 * @property string $actual
 */
class News extends CActiveRecord
{
        public $dir; 
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'news';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('category_id, title, short_story, full_story, date, keywords, description', 'required'),
			array('category_id', 'numerical', 'integerOnly'=>true),
			array('title, alt_title', 'length', 'max'=>150),
			//array('image', 'length', 'max'=>50),
                        array('image', 'file', 'types'=>'jpg, jpeg, gif, png','allowEmpty'=>true),
			array('keywords', 'length', 'max'=>255),
                        array('actual', 'length', 'max'=>1),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, category_id, title, alt_title, image, short_story, full_story, date, keywords, description, actual', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                    'category'=> array(self::BELONGS_TO, 'CategoryNews', 'category_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'category_id' => 'Категория',
			'title' => 'Заголовок',
			'alt_title' => 'Ссылка',
			'image' => 'Изображение',
			'short_story' => 'Краткое описание',
			'full_story' => 'Полное описание',
			'date' => 'Дата',
                        'keywords' => 'Keywords',
			'description' => 'Description',
			'actual' => 'Актуальное сегодня',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('category_id',$this->category_id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('alt_title',$this->alt_title,true);
		$criteria->compare('image',$this->image,true);
		$criteria->compare('short_story',$this->short_story,true);
		$criteria->compare('full_story',$this->full_story,true);
		$criteria->compare('date',$this->date,true);
                $criteria->compare('keywords',$this->keywords,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('actual',$this->actual,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return News the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
        
        public static function getLastNews($actual)
	{
		$criteria=new CDbCriteria;
                $criteria->select='id,title, alt_title, image, short_story, date';  // выбираем только поле 'id,title'
                $criteria->condition='actual=:actual';
                $criteria->params=array(':actual'=>$actual);
                $criteria->order = 'id DESC';
                $criteria->limit=8;
                $model = News::model()->findAll($criteria);
                return $model;
	}
        
        public function beforeSave()
    {
            $this->alt_title = Translite::rusencode($this->title);
            
        if($this->isNewRecord)
        {
            $this->image = '';
        }
        else 
        {
            $this->image = $this->image; 
        }
        
            Yii::import('ext.upload.Upload');
            $handle = new Upload($_FILES[News]);
    
            if ($handle->uploaded)
            { 
                $this->deleteImg();
                $this->dir = Yii::getPathOfAlias('webroot.upload.news').DIRECTORY_SEPARATOR;
                
                $new_name = $this->alt_title;
                if(strlen($new_name)>30)
                {
                   $new_name = substr($new_name, 0, 30);
                }
                $new_name = $new_name.'_'.time();
                
                   $handle->file_new_name_body   = $new_name;
                   $handle->image_convert        = 'jpg';
                   $handle->image_resize         = true;
                   $handle->image_ratio          = true;
                   $handle->image_ratio_crop     = true;
                   $handle->image_x              = 100;
                   $handle->image_y              = 70;
                   $handle->process($this->dir.'/_thumb');
                   if ($handle->processed) {
                   }
                   else {
                            echo 'error upload : ' . $handle->error;
                         }
                         
                   $handle->file_new_name_body   = $new_name;
                   $handle->image_convert        = 'jpg';
                   $handle->image_resize         = true;
                   $handle->image_ratio          = true;
                   //$handle->image_ratio_crop     = true;
                   $handle->image_x              = 200;
                   $handle->image_y              = 140;
                   $handle->process($this->dir);
                   if ($handle->processed) {
                   }
                   else {
                            echo 'error upload : ' . $handle->error;
                         }
                         
                   $this->image = $new_name;
                    $handle->clean();
            }
        
            return parent::beforeSave();
    }
    
    protected function beforeDelete(){
        $this->deleteImg(); // удалили модель? удаляем и файл
        //$this->deleteGallery();
        return parent::beforeSave();
    }
    
    public function deleteImg(){
        $this->dir = Yii::getPathOfAlias('webroot.upload.news').DIRECTORY_SEPARATOR;
        $imgPath1=$this->dir.'/_thumb/'.$this->image.'.jpg';
        $imgPath2=$this->dir.$this->image.'.jpg';
        if(is_file($imgPath1)) unlink($imgPath1);
        if(is_file($imgPath2)) unlink($imgPath2);
    }
        
        
}
